<template>
  <div class="amap-wrap" >
    <el-amap
      ref="map"
      vid="amapContainer"
      :zoom="zoom"
      :events="events"
      class="amap-demo">
      </el-amap>
  </div>

</template>

<script>
import { AMapManager, lazyAMapApiLoaderInstance } from 'vue-amap';
import { getLonLag } from "./common"
import { addressSetMapCenter } from "./location"
import { mapSetMarker,mapClearMarker } from "./marker"

export default {
  name: "Amap",
  props: {
    options:{type:Object,default:()=>{}}
  },
  data() {
    return {
      map: null,
      zoom: 18,
      events: {},
      lnglat: {}
    }
  },
  mounted() {
    const _this = this
    lazyAMapApiLoaderInstance.load().then(() => {
      this.mapCreate()
      this.map.on("click",function(e) {
        const lnglat = getLonLag(e)
        _this.lnglat = lnglat
        _this.$emit("lnglat",lnglat)
        _this.setMarker()
      })
    });
  },
  methods: {
    // 创建地图
    mapCreate() {
      this.map = new AMap.Map('amapContainer', {
        center: [116.404755,39.9],
        zoom: this.zoom
      });
      this.map.on("complete",() => {
        this.mapLoad()
      })
    },
    // 地图加载完成，可以回调方法
    mapLoad() {
      if(this.options && this.options.mapLoad) {
        this.$emit("mapLoad")
      }
    },
    setMapCenter(value) {
      addressSetMapCenter(value, this.map)
    },
    setMarker(lnglat) {
      mapSetMarker(lnglat || this.lnglat, this.map)
    },
    clearMarker() {
      mapClearMarker(this.map)
    },
    // 销毁地图
    mapDestroy() {
      // 写法和下面的if一个意思
      this.map && this.map.destroy()

      // if(this.map) {
      //   this.map.destroy()
      // }
    }
  }
}
</script>

<style lang="scss" scoped>
.amap-wrap {
  height: 100%;
}
</style>
